package com.lwl.leetcode;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lwl
 * @Description 给定一个仅包含数字 2-9 的字符串，返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
 * <p>
 * 给出数字到字母的映射如下（与电话按键相同）。注意 1 不对应任何字母。
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode.cn/problems/letter-combinations-of-a-phone-number
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 * @date 2023/7/28 10:46
 */
public class Code17LetterCombinations {

    @Test
    public void test() {
        List<String> strings = letterCombinations("23");
        strings.forEach(System.out::println);
    }

    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0) {
            return new ArrayList<String>();
        }
        char[][] numChars = new char[][]{
                {'a', 'b', 'c'},
                {'d', 'e', 'f'},
                {'g', 'h', 'i'},
                {'j', 'k', 'l'},
                {'m', 'n', 'o'},
                {'p', 'q', 'r', 's'},
                {'t', 'u', 'v'},
                {'w', 'x', 'y', 'z'}
        };
        char[] str = digits.toCharArray();
        ArrayList<String> res = new ArrayList<>();
        process(numChars, str, 0, new StringBuilder(), res);
        return res;
    }

    private void process(char[][] numChars, char[] str, int index, StringBuilder curStr, ArrayList<String> res) {
        if (index == str.length) {
            res.add(curStr.toString());
            return;
        }
        char[] numChar = numChars[(str[index] - '0') - 2];
        for (int i = 0; i < numChar.length; i++) {
            curStr.append(numChar[i]);
            process(numChars, str, index + 1, curStr, res);
            curStr.deleteCharAt(curStr.length() - 1);
        }
    }
}
